package com.abe.libcore.base.screen

import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.ViewGroup
import com.abe.libcore.utils.CommonUtils

/**
 *自适应缩放标准布局
 */
abstract class BScreenActivity : AppCompatActivity() {
    //是否需要自适应布局
    abstract fun isAutoZoom(): Boolean

    //是否正常设置标准宽度
    private var isScreenSetNormal: Boolean = false

    //获取标准宽度
    fun getStandardW(): Int {
        val designWidth = CommonUtils.getMetaData(this, "designWidth", 0)
        isScreenSetNormal = designWidth != null
        return if (isScreenSetNormal) designWidth as Int else 0
    }

    //获取缩放比例
    fun getScale(): Float {
        val displayMetrics = resources.displayMetrics
        val width = displayMetrics.widthPixels
        val designWidth = getStandardW()
        return if (isAutoZoom() && isScreenSetNormal) (width.toFloat() / designWidth.toFloat()) else 1.0F
    }

    override fun setContentView(layoutResID: Int) {
        val view = View.inflate(this, layoutResID, null)
        this.setContentView(view)
    }

    override fun setContentView(view: View) {
        CommonUtils.log("scale:" + getScale())
        if (isAutoZoom() && getScale() != 1.0F) {
            RelayoutTool.relayoutViewHierarchy(view, getScale())
        }
        super.setContentView(view)
    }

    override fun setContentView(view: View, params: ViewGroup.LayoutParams) {
        if (isAutoZoom()) {
            RelayoutTool.relayoutViewHierarchy(view, getScale())
            RelayoutTool.scaleLayoutParams(params, getScale())
        }
        super.setContentView(view, params)
    }
}